package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.domain.Record;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import entity.PageResult;
import entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 用户登录和注销Controller
 */
@Controller
@Slf4j

public class UserController {
    @RequestMapping("/toMainPage")
    public String  toMainPage(){
        return "main";
    }
    //注入userService
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper ;
    /*
   用户登录
    */
    @PostMapping("/login")
    public String login(User user, HttpServletRequest request){

        try {
            User u=userService.login(user);
            /*
            用户账号和密码是否查询出用户信息
                是：将用户信息存入Session，并跳转到后台首页
                否：Request域中添加提示信息，并转发到登录页面
             */
            if(u!=null){
                if (u.getStatus().equals("1")){
                    request.setAttribute("msg","用户已被禁用");
                    return  "forward:/admin/login.jsp";
                }
                request.getSession().setAttribute("USER_SESSION",u);
                request.getSession().setAttribute("USER_ROLE",u.getRole());
                return "redirect:/admin/main.jsp";
            }
            request.setAttribute("msg","用户名或密码错误");
            return  "forward:/admin/login.jsp";
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误,请等待业务修复");
            return  "forward:/admin/login.jsp";
        }
    }
/*
注销登录
 */
@RequestMapping("/logout")
public String logout( HttpServletRequest request){
    try {
        HttpSession session = request.getSession();
        //销毁Session
        session.invalidate();
        return  "forward:/admin/login.jsp";
    }catch (Exception e){
        e.printStackTrace();
        request.setAttribute("msg","系统错误,请等待业务修复");
        return  "forward:/admin/login.jsp";
    }
}
/*
注册
 */
@RequestMapping("/register")
public String register( User user,HttpServletRequest request){

    try {
        user.setStatus("0");
        user.setRole("USER");
        int add = userMapper.insert(user);

        if(add!=1)throw new Exception();
    }catch(DuplicateKeyException e){

        request.setAttribute("msg","已存在相同用户名");
        return  "forward:/admin/register.jsp";
    }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误,请等待业务修复");
            return  "forward:/admin/login.jsp";
    }

    return "forward:/admin/login.jsp";

}
@RequestMapping("/users")
public ModelAndView users(User user, HttpServletRequest request, Integer pageNum, Integer pageSize){

    if (pageNum == null) {
        pageNum = 1;
    }
    if (pageSize == null) {
        pageSize = 10;
    }
    //查询到的用户信息
    PageResult pageResult = userService.search(user, pageNum, pageSize);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("users");
    //将查询到的数据存放在 ModelAndView的对象中
    modelAndView.addObject("pageResult", pageResult);
    //将查询的参数返回到页面，用于回显到查询的输入框中
    modelAndView.addObject("search", user);
    //将当前页码返回到页面，用于分页插件的分页显示
    modelAndView.addObject("pageNum", pageNum);
    //将当前查询的控制器路径返回到页面，页码变化时继续向该路径发送请求
    modelAndView.addObject("gourl", request.getRequestURI());
    return modelAndView;
}
    @RequestMapping("/searchUsers")
    public ModelAndView searchUsers(User user, HttpServletRequest request, Integer pageNum, Integer pageSize){
        if(pageNum==null){
            pageNum=1;
        }
        if(pageSize==null){
            pageSize=10;
        }

        PageResult pageResult=userService.searchUsers(user,pageNum,pageSize);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("users");
        //将查询到的数据存放在 ModelAndView的对象中
        modelAndView.addObject("pageResult",pageResult);
        //将查询的参数返回到页面，用于回显到查询的输入框中
        modelAndView.addObject("search",user);
        //将当前页码返回到页面，用于分页插件的分页显示
        modelAndView.addObject("pageNum",pageNum);
        //将当前查询的控制器路径返回到页面，页码变化时继续向该路径发送请求
        modelAndView.addObject("gourl", request.getRequestURI());
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/startOrStopUser")
    public Result startOrStopUser(String email) {
        try {
            Integer count=userService.startOrStopUser(email);
            if(count!=1){
                return new Result(false, "确认失败!");
            }
            return new Result(true, "确认成功!");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "确认失败!");
        }
    }
}
